package top.bbman.boot.auth.component;

import com.alicp.jetcache.Cache;
import com.alicp.jetcache.anno.CachePenetrationProtect;
import com.alicp.jetcache.anno.CacheType;
import com.alicp.jetcache.anno.CreateCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import top.bbman.boot.auth.constent.CoreIdCacheKeyType;
import top.bbman.boot.auth.key.PrefixedCacheKey;
import top.bbman.boot.auth.service.PeaBizUserService;
import top.bbman.boot.repository.constant.PeaBeanName;
import top.bbman.boot.repository.constant.PeaCacheName;

import javax.annotation.PostConstruct;
import java.util.concurrent.TimeUnit;

/**
 * @author 祥霸
 * @version 1.0.0
 */
@Component(PeaBeanName.Auth.LOGIN)
public class LoginComponent {

    @Autowired
    private PeaBizUserService peaBizUserService;

    /**
     * 这个缓存储存4中主账号对应关系，分别是 token unionid openid phone
     */
    @CreateCache(cacheType = CacheType.LOCAL, name = PeaCacheName.Auth.ID_BY_OTHER, expire = 30, timeUnit = TimeUnit.DAYS)
    @CachePenetrationProtect
    private Cache<PrefixedCacheKey<CoreIdCacheKeyType, String>, String> idByOtherCache;

    @PostConstruct
    private void init() {
        this.idByOtherCache.config().setLoader(this::loadIdByOtherCache);
    }

    private String loadIdByOtherCache(PrefixedCacheKey<CoreIdCacheKeyType, String> key) {
        return peaBizUserService.getIdByOther(key.getPrefix(), key.getValue());
    }

    public String findIdByToken(String token) {
        PrefixedCacheKey<CoreIdCacheKeyType, String> key = new PrefixedCacheKey<>(CoreIdCacheKeyType.TOKEN, token);
        return idByOtherCache.get(key);
    }

    public void putIdByToken(String token, String userId) {
        PrefixedCacheKey<CoreIdCacheKeyType, String> key = new PrefixedCacheKey<>(CoreIdCacheKeyType.TOKEN, token);
        idByOtherCache.put(key, userId);
    }

    public void removeIdByToken(String token) {
        PrefixedCacheKey<CoreIdCacheKeyType, String> key = new PrefixedCacheKey<>(CoreIdCacheKeyType.TOKEN, token);
        idByOtherCache.remove(key);
    }
}
